package com.poisonh.unifiedauth.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.poisonh.unifiedauth.R;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private String body;
    private String bod;
    private String nickname;
    private String headimgurl;
    private String unionid;



    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxentry);
        api= WXAPIFactory.createWXAPI(WXEntryActivity.this,"wxd933db7e5fcef507");
        api.registerApp("wxd933db7e5fcef507");
        //等待微信回调
        api.handleIntent(getIntent(), this);
    }




    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {


    }



    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp baseResp) {
        Bundle bundle=getIntent().getExtras();
        SendAuth.Resp resp=new SendAuth.Resp(bundle);//这个是登陆必须用到的，要用来获取code值的。
        //而区分分享回调返回的结果和登陆回调返回的结果   是用baseResp.getType()== ConstantsAPI.COMMAND_SENDAUTH
        //和baseResp.getType()==ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX
        //注意哈 这里的baseResp和resp是不同的哈。resp这个是登陆用到的


        //获取到code之后，需要调用接口获取到access_token
        if(baseResp.errCode==BaseResp.ErrCode.ERR_OK){
            if(baseResp.getType()== ConstantsAPI.COMMAND_SENDAUTH){
                //登陆结果回调
              //  String code=resp.token;

             //   getAsync("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxa7e01ec6967ae86f&secret=15dc8d8c7b06d991b7f32127bb6aa3ae&code="+code+"&grant_type=authorization_code");
            }else if(baseResp.getType()==ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){
                Toast.makeText(WXEntryActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                finish();
            }

        }else {
            WXEntryActivity.this.finish();
        }
    }


    //微信登录的方法
    private void getAsync(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    String str = response.cacheResponse().toString();
                    Log.e("wangshu", "cache---" + str);
                } else {
                    body=response.body().string();
                    String str = response.networkResponse().toString();
                    Log.e("wangshu", "network---" + str);
                    Log.e("body", "body---" + body);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jsonObject=new JSONObject(body);

                                String access_token=jsonObject.getString("access_token");
                                int expires_in=jsonObject.getInt("expires_in");
                                String refresh_token=jsonObject.getString("refresh_token");
                                String openid=jsonObject.getString("openid");
                                String scope=jsonObject.getString("scope");
                                String unionid=jsonObject.getString("unionid");
                                getAsyncpersonData("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid);

                                Log.e("access_token\n",access_token);
                                Log.e("expires_in\n", String.valueOf(expires_in));
                                Log.e("refresh_token\n",refresh_token);
                                Log.e("openid\n",openid);
                                Log.e("scope\n",scope);
                                Log.e("unionid\n",unionid);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();

                        }
                    });
                }

            }
        });
    }


    private void getAsyncpersonData(String url) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    String str = response.cacheResponse().toString();
                    Log.e("wangshu", "cache---" + str);
                } else {
                    bod=response.body().string();

                    String str = response.networkResponse().toString();

                    Log.e("wangshu", "network---" + str);
                    Log.e("bod", "bod---" + bod);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jsonObject=new JSONObject(bod);

                                nickname=jsonObject.getString("nickname");//微信用户昵称
                                headimgurl=jsonObject.getString("headimgurl");//微信用户头像
                                unionid=jsonObject.getString("unionid");//用户统一标识


                                SharedPreferences sharedPreferences=getSharedPreferences("weixinSave", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor=sharedPreferences.edit();
                                editor.putString("nickname",nickname);
                                editor.putString("headimgurl",headimgurl);
                                editor.putString("unionid",unionid);
                                editor.commit();
                                // String nickname=jsonObject.getString("nickname");

                                //Glide.with(WXEntryActivity.this).load(headimgurl);
                                Log.e("access_token",nickname);
                                Log.e("refresh_token",headimgurl);
                                Log.e("openid",unionid);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();


//                            SharedPreferences sharedPreferences_wx=getSharedPreferences("landingwx",Context.MODE_PRIVATE);
//                            String land=sharedPreferences_wx.getString("landingwx","");
//                            if("oneland".equals(land)){
//                                Intent intent=new Intent(WXEntryActivity.this, MainActivity.class);
//                                startActivity(intent);
//                                finish();
//
//                            }else if("meland".equals(land)){
//
//                                Intent intentdis=new Intent();
//                                intentdis.setAction("com.example.bluetooth.le.WX");
//                                intentdis.putExtra("name",nickname);
//                                intentdis.putExtra("headurl",headimgurl);
//                                sendBroadcast(intentdis);
//                                finish();
//                            }


                        }
                    });
                }

            }
        });
    }

}
